package com.rlz.net.Interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * Created by RLZ
 * on 2021/4/16
 *
 */
class NetCacheInterceptor : Interceptor {

    //为0的时候 不使用缓存
    private var mOnlineCacheTime = 0

    companion object {
        val instance: NetCacheInterceptor by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetCacheInterceptor()
        }
    }

    fun setOnlineTime(time: Int) {
        mOnlineCacheTime = time
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request: Request = chain.request()
        val newBuilder: Request.Builder = request.newBuilder()

        request = newBuilder.build()

        val response: Response = chain.proceed(request)

        /*//不使用 cookie的方式去处理 token
        val token = CacheManager.get().token as String
        if (!TextUtils.isEmpty(token))
            newBuilder.addHeader("Token", token).build()

        request = newBuilder.build()

        val response: Response = chain.proceed(request)

        val list = response.headers.values("Token")

        if (list.size > 0) {
            //添加token
        }*/

        return if (mOnlineCacheTime != 0) {
            //如果有时间就设置缓存
            val temp = mOnlineCacheTime
            val response1 = response.newBuilder()
                    .header("Cache-Control", "public, max-age=$temp")
                    .removeHeader("Pragma")
                    .build()
            mOnlineCacheTime = 0
            response1
        } else {
            //如果没有时间就不缓存
            response.newBuilder()
                    .header("Cache-Control", "no-cache")
                    .removeHeader("Pragma")
                    .build()
        }
    }
}